//
//  MineViewController.m
//  HelpThePoor
//
//  Created by van7ish on 2016/11/25.
//  Copyright © 2016年 van7ish. All rights reserved.
//

#import "MineViewController.h"
#import "HistoryViewController.h"
#import "LoginViewController.h"
#import "ShelfViewController.h"
#import "RegistViewController.h"
#import "IdentityVerifyViewController.h"
#import "PhoneVerifyViewController.h"

@interface MineViewController () <UITableViewDelegate, UITableViewDataSource, UITextViewDelegate, LoginDelegate>

/** 头视图 */
@property (nonatomic, strong) UIImageView * headerImageView;
/** 登录按钮 */
@property (nonatomic, strong) UIButton * loginButton;
/** 立即登录 */
@property (nonatomic, strong) UIButton * loginLabel;
/** 个人中心列表 */
@property (nonatomic, strong) UITableView * mineTableView;
/** 退出登录按钮 */
@property (nonatomic, strong) UIButton * logoutButton;
/** 意见反馈弹窗 */
@property (nonatomic, strong) UIView * feedbackAlert;


@end

@implementation MineViewController

- (UIView *)feedbackAlert{
    if (!_feedbackAlert) {
        
        _feedbackAlert = [[UIView alloc] initWithFrame:self.view.bounds];
        _feedbackAlert.backgroundColor = COLOR_alphaBGCOLOR;
        
        UIView * alert = [[UIView alloc] initWithFrame:CGRectMake(WidthScale(40), HeightScale(160), WidthScale(334), HeightScale(215))];
        alert.layer.cornerRadius = WidthScale(10);
        alert.layer.masksToBounds = YES;
        alert.backgroundColor = COLOR_WHITE;
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, alert.frame.size.width, HeightScale(40))];
        label.text = @"  意见反馈";
        label.backgroundColor = COLOR_GREEN;
        label.textColor = COLOR_WHITE;
        label.font = FONTSIZE(17);
        
        UIButton *cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(alert.frame.size.width - WidthScale(34), HeightScale(10), WidthScale(20), HeightScale(20))];
        [cancelButton setImage:ImageNamed(@"cha") forState:UIControlStateNormal];
        [cancelButton initWithBlock:^(id obj) {
            DLog(@"取消");
            [_feedbackAlert removeFromSuperview];
            
        } for:UIControlEventTouchUpInside];
        
        UITextView *textView =[[UITextView alloc] initWithFrame:CGRectMake(WidthScale(5), CGRectGetMaxY(label.frame), alert.frame.size.width - WidthScale(10), alert.frame.size.height - label.frame.size.height - HeightScale(44))];
        textView.text = @"请输入您的反馈意见…";
        textView.textColor = [UIColor blackColor];
        textView.font = FONTSIZE(15);
        textView.showsVerticalScrollIndicator = NO;
        
        
        UITextView *textViewFore = [[UITextView alloc] initWithFrame:CGRectMake(textView.frame.origin.x, textView.frame.origin.y, textView.frame.size.width, textView.frame.size.height)];
        textViewFore.alpha = 0.8;
        textViewFore.textColor = COLOR_FONTBLACK;
        textViewFore.delegate = self;
        textViewFore.font = FONTSIZE(15);
        textViewFore.showsVerticalScrollIndicator = NO;
        textViewFore.tag = 10;
        
        UIButton *submitButton = [[UIButton alloc] initWithFrame:CGRectMake(alert.frame.size.width - WidthScale(76), alert.frame.size.height - HeightScale(44), WidthScale(70), HeightScale(44))];
        [submitButton setImage:ImageNamed(@"tijiao") forState:UIControlStateNormal];
        __weak typeof(self)weakSelf = self;
        [submitButton initWithBlock:^(id obj) {
            DLog(@"提交意见反馈");
            
            [weakSelf requestFeedBack];
            
        } for:UIControlEventTouchUpInside];
        
        [alert addSubview:label];
        [alert addSubview:cancelButton];
        [alert addSubview:textView];
        [alert addSubview:textViewFore];
        [alert addSubview:submitButton];
        [_feedbackAlert addSubview:alert];
    }
    return _feedbackAlert;
}

- (UIButton *)logoutButton{
    if (!_logoutButton) {
        _logoutButton = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_W - WidthScale(150)) / 2, self.mineTableView.frame.size.height - HeightScale(70), WidthScale(150), HeightScale(34))];
        [_logoutButton setImage:ImageNamed(@"sign-out_s") forState:UIControlStateNormal];
        
        _logoutButton.hidden = YES;
        
        __weak typeof(self)weakSelf = self;
        [_logoutButton initWithBlock:^(id obj) {
            DLog(@"退出登录");
            
            [ZRProgressHUD showProgress:nil inView:self.view];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [ZRProgressHUD showSuccess:@"退出登录成功" inview:weakSelf.view];
                
                //删除本地搜索历史记录
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"searchKeyWords"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                [AppDelegate shareDelegate].userModel = nil;
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"user"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                weakSelf.loginButton.enabled = YES;
                weakSelf.loginLabel.enabled = YES;
                _logoutButton.hidden = YES;
                
                [self.mineTableView reloadData];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"logoutSuccess" object:nil];
                
            });
            
        } for:UIControlEventTouchUpInside];
    }
    return _logoutButton;
}

- (UITableView *)mineTableView{
    if (!_mineTableView) {
        _mineTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headerImageView.frame), SCREEN_W, SCREEN_H - self.headerImageView.frame.size.height - self.tabBarController.tabBar.height) style:UITableViewStyleGrouped];
        _mineTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, HeightScale(5))];
        _mineTableView.tableFooterView = [UIView new];
        _mineTableView.backgroundColor = COLOR_DEEPBGCOLOR;
        _mineTableView.bounces = NO;
        _mineTableView.delegate = self;
        _mineTableView.dataSource = self;
        _mineTableView.rowHeight = HeightScale(60);
        _mineTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_mineTableView addSubview:self.logoutButton];
        
        
        if (@available(iOS 11.0, *)) {
            _mineTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
        }
    }
    return _mineTableView;
}

- (UIButton *)loginLabel{
    if (!_loginLabel) {
        _loginLabel = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_W - WidthScale(160)) / 2, CGRectGetMaxY(_loginButton.frame), WidthScale(160), HeightScale(36))];
        [_loginLabel setTitle:@"立即登录" forState:UIControlStateNormal];
        _loginLabel.titleLabel.font = FONTSIZE(17);
        [_loginLabel setTitleColor:COLOR_WHITE forState:UIControlStateNormal];
        __weak typeof(self)weakSelf = self;
        [_loginLabel initWithBlock:^(id obj) {
            [weakSelf loginPresent];
        } for:UIControlEventTouchUpInside];
    }
    return _loginLabel;
}

- (UIButton *)loginButton{
    if (!_loginButton) {
        _loginButton = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_W - WidthScale(80)) / 2, (self.headerImageView.frame.size.height - HeightScale(80)) / 2 - 10, WidthScale(80), HeightScale(80))];
        [_loginButton setImage:ImageNamed(@"yonghu") forState:UIControlStateNormal];
        __weak typeof(self)weakSelf = self;
        [_loginButton initWithBlock:^(id obj) {
            DLog(@"登录");
            [weakSelf loginPresent];
        } for:UIControlEventTouchUpInside];
    }
    return _loginButton;
}

- (UIImageView *)headerImageView{
    if (!_headerImageView) {
        _headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_W / 1.68)];
        _headerImageView.image = [UIImage imageNamed:@"gerenzhongxin_top_banner"];
        _headerImageView.userInteractionEnabled = YES;
    }
    return _headerImageView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = COLOR_LIGHTBGCOLOR;

    [self.view addSubview:self.headerImageView];
    [self.headerImageView addSubview:self.loginButton];
    [self.headerImageView addSubview:self.loginLabel];
    [self.view addSubview:self.mineTableView];
    
    if ([AppDelegate shareDelegate].userModel) {
        [self loginSuccess];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:@"loginSuccess" object:nil];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if ([AppDelegate shareDelegate].userModel.actualName != nil) {
        [self.loginLabel setTitle:[NSString stringWithFormat:@"%@", [AppDelegate shareDelegate].userModel.actualName] forState:UIControlStateDisabled];
    } else {
        [self.loginLabel setTitle:[NSString stringWithFormat:@"%@", [AppDelegate shareDelegate].userModel.userName] forState:UIControlStateDisabled];
    }

    
    [self.mineTableView reloadData];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [UIView animateWithDuration:0.1 animations:^{
        [AppDelegate shareDelegate].tabBar.customBar.center = CGPointMake(SCREEN_W / 2, SCREEN_H - [AppDelegate shareDelegate].tabBar.customBar.frame.size.height / 2);
    }];
    
    [Tool setNavigationBarType:self];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)dealloc{
    DLog(@"%s", __func__);
}

#pragma mark - UITableViewDataSource Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if ([AppDelegate shareDelegate].userModel) {
        //已登录
        if (![AppDelegate shareDelegate].userModel.idNumber || ![AppDelegate shareDelegate].userModel.mobileNumber) {
            //没有手机号  或者  没有身份证号
            return 5;
        } else {
            return 4;
        }
    } else {
        return 4;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    cell.backgroundColor = COLOR_LIGHTBGCOLOR;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (indexPath.section == 0) {
        cell.imageView.image = ImageNamed(@"liulanlishi");
        cell.textLabel.text = @"浏览历史";
        cell.textLabel.font = FONTSIZE(17);
        UIImageView *accessoryImageView = [[UIImageView alloc] initWithImage: ImageNamed(@"箭头-(4)-拷贝-2")];
        cell.accessoryView = accessoryImageView;
    } else if (indexPath.section == 1) {
        cell.imageView.image = ImageNamed(@"huancunqingli");
        cell.textLabel.text = @"缓存清理";
        cell.textLabel.font = FONTSIZE(17);
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%luM", [[SDImageCache sharedImageCache] getSize] / 1000 / 1000];
        cell.detailTextLabel.font = FONTSIZE(17);
        cell.detailTextLabel.textColor = COLOR_GREEN;
    } else if (indexPath.section == 2) {
        cell.imageView.image = ImageNamed(@"yijianfankui");
        cell.textLabel.text = @"意见反馈";
        cell.textLabel.font = FONTSIZE(17);
        UIImageView *accessoryImageView = [[UIImageView alloc] initWithImage: ImageNamed(@"箭头-(4)-拷贝-2")];
        cell.accessoryView = accessoryImageView;

    } else if (indexPath.section == 3) {
        cell.imageView.image = ImageNamed(@"shujia");
        cell.textLabel.text = @"我的书架";
        cell.textLabel.font = FONTSIZE(17);
        UIImageView *accessoryImageView = [[UIImageView alloc] initWithImage: ImageNamed(@"箭头-(4)-拷贝-2")];
        cell.accessoryView = accessoryImageView;
    } else if (indexPath.section == 4) {
        if ([AppDelegate shareDelegate].userModel.mobileNumber) {
            cell.imageView.image = ImageNamed(@"实名认证");
            cell.textLabel.text = @"实名认证";
        } else {
            cell.imageView.image = ImageNamed(@"手机号");
            cell.textLabel.text = @"绑定手机号";
        }
        
        cell.textLabel.font = FONTSIZE(17);
        UIImageView *accessoryImageView = [[UIImageView alloc] initWithImage: ImageNamed(@"箭头-(4)-拷贝-2")];
        cell.accessoryView = accessoryImageView;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if ([AppDelegate shareDelegate].userModel) {
            DLog(@"浏览历史");
            HistoryViewController *historyVC = [[HistoryViewController alloc] init];
            [self.navigationController pushViewController:historyVC animated:YES];
        } else {
            DLog(@"登录")
            [self loginPresent];
        }
        
    } else if (indexPath.section == 1) {
        DLog(@"缓存清理");
        [[SDImageCache sharedImageCache] clearDiskOnCompletion:nil];
        [ZRProgressHUD showProgress:nil inView:self.view];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [ZRProgressHUD showSuccess:@"缓存清理成功" inview:self.view];
            [self.mineTableView reloadData];
        });

        
    } else if (indexPath.section == 2) {
        if ([AppDelegate shareDelegate].userModel) {
            DLog(@"意见反馈");
            [[AppDelegate shareDelegate].window addSubview:self.feedbackAlert];
            UITextView *textViewFore = (UITextView *)[self.feedbackAlert viewWithTag:10];
            [textViewFore becomeFirstResponder];
        } else {
            DLog(@"登录");
            [self loginPresent];
        }
        
    } else if (indexPath.section == 3) {
        DLog(@"我的书架");
        if ([AppDelegate shareDelegate].userModel) {
            ShelfViewController *shelfVC = [[ShelfViewController alloc] init];
            [self.navigationController pushViewController:shelfVC animated:YES];
        } else {
            DLog(@"登录");
            [self loginPresent];
        }
    } else if (indexPath.section == 4) {
        if ([AppDelegate shareDelegate].userModel.mobileNumber) {
            IdentityVerifyViewController *verifyVC = [[IdentityVerifyViewController alloc] init];
            [self presentViewController:verifyVC animated:YES completion:nil];
        } else {
            PhoneVerifyViewController *verifyVC = [[PhoneVerifyViewController alloc] init];
            [self presentViewController:verifyVC animated:YES completion:nil];
        }
        
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return HeightScale(5);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return HeightScale(5);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

#pragma mark - UITextViewDelegate Method

- (void)textViewDidChange:(UITextView *)textView{
    if ([textView.text length] == 0) {
        textView.alpha = 0.8;
    } else {
        textView.alpha = 1;
    }
}

- (void)registPresent{
    RegistViewController *registVC = [[RegistViewController alloc] init];
    [self presentViewController:registVC animated:YES completion:nil];
}

#pragma mark - 事件处理

- (void)loginPresent{
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    loginVC.delegate = self;
    [self presentViewController:loginVC animated:YES completion:nil];
}

- (void)loginSuccess{
    
    NSData *userData = [[NSUserDefaults standardUserDefaults] objectForKey:@"user"];
    
    NSDictionary *userDic = [NSKeyedUnarchiver unarchiveObjectWithData:userData];
    
    [AppDelegate shareDelegate].userModel = [UserModel modelWithDictionary:userDic];
    
    if ([AppDelegate shareDelegate].userModel.actualName != nil) {
        [self.loginLabel setTitle:[NSString stringWithFormat:@"%@", [AppDelegate shareDelegate].userModel.actualName] forState:UIControlStateDisabled];
    } else {
        [self.loginLabel setTitle:[NSString stringWithFormat:@"%@", [AppDelegate shareDelegate].userModel.userName] forState:UIControlStateDisabled];
    }
    
    self.loginLabel.enabled = NO;
    self.loginButton.enabled = NO;
    
    self.logoutButton.hidden = NO;
    
    [self.mineTableView reloadData];
    
    DLog(@"%@", [AppDelegate shareDelegate].userModel.userId);
}



#pragma mark - data request

- (void)requestFeedBack{
    UITextView *textViewFore = (UITextView *)[self.feedbackAlert viewWithTag:10];
    NSString *URL = [NSString stringWithFormat:KFeedBackURL, KHostAddress, [AppDelegate shareDelegate].userModel.userId, [AppDelegate shareDelegate].userModel.userName, @"", textViewFore.text, [AppDelegate shareDelegate].userModel.mobileNumber, @(1)];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            [ZRProgressHUD showMsgWithoutView:@"提交成功"];
            [self.feedbackAlert removeFromSuperview];
            self.feedbackAlert = nil;
        } else {
            [ZRProgressHUD showMsgWithoutView:@"提交失败，请稍后再试"];
            [self.feedbackAlert removeFromSuperview];
        }
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}

@end
